from flask import Blueprint, render_template, jsonify, request
from models import BigHouse, User, Recommend
from sqlalchemy import func
from utils.regression_data import linear_model_main
from settings import db
from utils.pearson_recommend import recommend
from datetime import datetime, timedelta

detail_page = Blueprint('detail_page', __name__)


# 实现房源数据展示
@detail_page.route('/house/<int:hid>')
def detail(hid):
    house = BigHouse.query.get(hid)
    facilities_str = house.facilities
    facilities_list = facilities_str.split('-')
    name = request.cookies.get('name')
    recommend_li = []

    if name:
        user = User.query.filter(User.name == name).first()
        seen_id_str = user.seen_id
        if seen_id_str:
            seen_id_list = seen_id_str.split(',')
            set_id = set([int(i) for i in seen_id_list])
            if hid not in set_id:
                new_seen_id_str = seen_id_str + ',' + str(hid)
                user.seen_id = new_seen_id_str
                db.session.commit()
        else:
            user.seen_id = str(hid)
            db.session.commit()

        info = Recommend.query.filter(Recommend.user_id == user.id, Recommend.house_id == house.id).first()
        if info:
            new_score = info.score + 1
            info.score = new_score
            db.session.commit()
        else:
            new_info = Recommend(user_id=user.id, house_id=house.id, title=house.title, address=house.address,
                                 block=house.block, score=1)
            db.session.add(new_info)
            db.session.commit()

        result = recommend(user.id)
        if result:
            for recommend_hid, recommend_num in result:
                recommend_house = BigHouse.query.get(int(recommend_hid))
                recommend_li.append(recommend_house)
        else:
            ordinary_recommend = BigHouse.query.filter(BigHouse.address == house.address).order_by(
                BigHouse.page_views.desc()).all()
            recommend_li = ordinary_recommend[:6] if len(ordinary_recommend) > 6 else ordinary_recommend
    else:
        ordinary_recommend = BigHouse.query.filter(BigHouse.address == house.address).order_by(
            BigHouse.page_views.desc()).all()
        recommend_li = ordinary_recommend[:6] if len(ordinary_recommend) > 6 else ordinary_recommend

    return render_template('detail_page.html', house=house, facilities=facilities_list, recommend_li=recommend_li)


# 实现户型占比功能
@detail_page.route('/get/piedata/<block>')
def return_pie_data(block):
    result = BigHouse.query.with_entities(BigHouse.rooms, func.count()).filter(BigHouse.block == block).group_by(
        BigHouse.rooms).order_by(func.count().desc()).all()
    data = [{'name': one_house[0], 'value': one_house[1]} for one_house in result]
    return jsonify({'data': data})


# 实现本地区小区数量TOP20功能
@detail_page.route('/get/columndata/<block>')
def return_bar_data(block):
    result = BigHouse.query.with_entities(BigHouse.address, func.count()).filter(BigHouse.block == block).group_by(
        BigHouse.address).order_by(func.count().desc()).all()
    name_list = []
    num_list = []
    for addr, num in result:
        residence_name = addr.rsplit('-', 1)[1]
        name_list.append(residence_name)
        num_list.append(num)
    data = {'name_list_x': name_list[:20], 'num_list_y': num_list[:20]} if len(name_list) > 20 else {
        'name_list_x': name_list, 'num_list_y': num_list}
    return jsonify({'data': data})


# 实现房价预测功能
@detail_page.route('/get/scatterdata/<block>')
def return_scatter_data(block):
    result = BigHouse.query.with_entities(func.avg(BigHouse.price / BigHouse.area)).filter(
        BigHouse.block == block).group_by(BigHouse.publish_time).order_by(BigHouse.publish_time).all()
    time_stamp = BigHouse.query.filter(BigHouse.block == block).with_entities(BigHouse.publish_time).all()
    time_stamp.sort(reverse=True)
    date_li = [datetime.fromtimestamp(int(time_stamp[0][0])).strftime("%m-%d") + timedelta(days=-i) for i in
               range(1, 30)]
    date_li.reverse()

    data = []
    x = []
    y = []
    for index, i in enumerate(result):
        x.append([index])
        y.append(round(i[0], 2))
        data.append([index, round(i[0], 2)])

    predict_value = len(data)
    predict_outcome = linear_model_main(x, y, predict_value)
    p_outcome = round(predict_outcome[0], 2)
    data.append([predict_value, p_outcome])
    return jsonify({'data': {'data-predict': data, 'date_li': date_li}})


# 实现户型价格走势
@detail_page.route('/get/brokenlinedata/<block>')
def return_brokenline_data(block):
    time_stamp = BigHouse.query.filter(BigHouse.block == block).with_entities(BigHouse.publish_time).all()
    time_stamp.sort(reverse=True)
    date_li = [datetime.fromtimestamp(int(time_stamp[0][0])).strftime("%m-%d") + timedelta(days=-i) for i in
               range(1, 14)]
    date_li.reverse()

    data = []
    data1 = []
    data2 = []
    data3 = []

    result = BigHouse.query.with_entities(func.avg(BigHouse.price / BigHouse.area)).filter(BigHouse.block == block,
                                                                                           BigHouse.rooms == '1室1厅').group_by(
        BigHouse.publish_time).order_by(BigHouse.publish_time).all()
    data = [round(i[0], 2) for i in result[-14:]]

    result1 = BigHouse.query.with_entities(func.avg(BigHouse.price / BigHouse.area)).filter(BigHouse.block == block,
                                                                                            BigHouse.rooms == '2室1厅').group_by(
        BigHouse.publish_time).order_by(BigHouse.publish_time).all()
    data1 = [round(i[0], 2) for i in result1[-14:]]

    result2 = BigHouse.query.with_entities(func.avg(BigHouse.price / BigHouse.area)).filter(BigHouse.block == block,
                                                                                            BigHouse.rooms == '2室2厅').group_by(
        BigHouse.publish_time).order_by(BigHouse.publish_time).all()
    data2 = [round(i[0], 2) for i in result2[-14:]]

    result3 = BigHouse.query.with_entities(func.avg(BigHouse.price / BigHouse.area)).filter(BigHouse.block == block,
                                                                                            BigHouse.rooms == '3室2厅').group_by(
        BigHouse.publish_time).order_by(BigHouse.publish_time).all()
    data3 = [round(i[0], 2) for i in result3[-14:]]

    return jsonify({'data': {'1室1厅': data, '2室1厅': data1, '2室2厅': data2, '3室2厅': data3, 'date_li': date_li}})


def deal_traffic_txt(word):
    return '暂无信息！' if len(word) == 0 or word is None else word


detail_page.add_app_template_filter(deal_traffic_txt, 'dealNone')
